//
//  TableClockViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/18/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TableClockViewController.h"

@interface TableClockViewController ()

@end

@implementation TableClockViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    [self setClockToMinutes:2 andSeconds:0];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
}
-(void) show
{
    [self.view setHidden:NO];
    [self setClockToMinutes:0 andSeconds:30];
    
}
-(void) hide
{
     [self.view setHidden:YES];
}
- (void)timerTick:(NSTimer *)theTimer 
{
    [self decTime];
}


- (void)decTime
{
    if ( min == 0 && sec == 0 )
    {
        return;
    }
    
    sec--;
    
    if ( sec < 0 )
    {
        sec = 59;
        min--;
    }
    
    [self setClockToMinutes:min andSeconds:sec];
    
    if ( min == 0 && sec == 0 )
    {
        [timer invalidate];
        timer = nil;
        //TODO: delegate
    }
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

- (void)setClockToMinutes:(int)minutes andSeconds:(int)seconds
{
    min = (minutes < 0) ? 0 : (minutes > 99 ? 99 : minutes);  
    sec = (seconds < 0) ? 0 : (seconds > 59 ? 59 : seconds);  
    [self updateLabels];
}

- (void)runClockWithMinutes:(int)minutes andSeconds:(int)seconds
{
    min = (minutes < 0) ? 0 : (minutes > 99 ? 99 : minutes);  
    sec = (seconds < 0) ? 0 : (seconds > 59 ? 59 : seconds);  
    [self updateLabels];
    [self run];
}



- (void)run
{
    if ( timer != nil )
    {
        return;
    }
    
    if ( min > 0 || sec > 0 )
    {
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
    }
}

- (void)pause
{
    if ( timer != nil )
    {
        [timer invalidate];
        timer = nil;
    }
}



- (void)rewind
{
    if ( timer != nil )
    {
        [timer invalidate];
        timer = nil;
    }
    
    [self setClockToMinutes:0 andSeconds:0];
}

- (void)updateLabels
{
    minLabel.text  = [NSString stringWithFormat:@"%d %d", min / 10, min % 10];
    secLabel.text  = [NSString stringWithFormat:@"%d %d", sec / 10, sec % 10];
}

@end